package com.fly.feishu.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fly.feishu.api.utils.NotifyDataDecrypter;
import com.fly.feishu.web.lisener.FeishuTopicListener;
import com.fly.feishu.web.lisener.register.FeishuTopicRegister;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/feishu")
@Slf4j
public class FeishuController {

    @Value("${feishu.encrypt-key}")
    private String encrptKey;

    /**
     * 用于SSO回调
     */
    @RequestMapping("/ssoBackCall")
    public void ssoBackCall(String code, String state) {

    }

    /**
     * @param body
     * @return
     */
    @RequestMapping("/pub/event")
    private JSONObject eventData(@RequestBody String body) {
        log.info("飞书事件订阅请求，body = {}", body);
        JSONObject jsonResponse = JSON.parseObject(body);
        JSONObject jsonObject = JSON.parseObject(NotifyDataDecrypter.decrypt(encrptKey, jsonResponse.get("encrypt").toString()));
        log.info("飞书事件订阅请求,解析后的结果为 = {}", jsonObject);
        try {
            String type = jsonObject.getJSONObject("event").getString("type");
            FeishuTopicListener listener = FeishuTopicRegister.getListener(type);
            listener.exec(jsonObject.getJSONObject("event"));
        }catch (Exception e) {
            log.error("飞书事件订阅请求回调，业务方法执行失败, param = {}", body, e);
        }

        return jsonObject;
    }
}
